package com.maychat.service.impl;

import com.maychat.enums.ContactType;
import com.maychat.enums.MessageType;
import com.maychat.enums.UserContactStatus;
import com.maychat.mapper.ChatSessionUserMapper;
import com.maychat.mapper.UserContactMapper;
import com.maychat.pojo.ChatSessionUser;
import com.maychat.pojo.UserContact;
import com.maychat.pojo.extended.Message;
import com.maychat.service.ChatSessionUserService;
import com.maychat.websocket.MessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChatSessionUserServiceImpl implements ChatSessionUserService {

    @Autowired
    private ChatSessionUserMapper chatSessionUserMapper;

    @Autowired
    MessageHandler messageHandler;
    @Autowired
    private UserContactMapper userContactMapper;

    public void updateRedundant(String contactId, String contactName) {
        ChatSessionUser update = new ChatSessionUser();
        update.setContactId(contactId);
        update.setContactName(contactName);
        chatSessionUserMapper.updateChatSessionUserByContactId(update);
        Message<Object> msg = new Message<>();
        ContactType type = ContactType.getByPrefix(contactId);
        switch (type) {
            case GROUP -> {
                msg.setContactType(type.ordinal());
                msg.setContactId(contactId);
                msg.setContactName(contactName);
                msg.setMessageType(MessageType.CONTACT_NAME_UPDATE.ordinal());
                msg.setExtendedData(update);
                messageHandler.sendMsg(msg);
            }
            case USER -> {
                UserContact query = new UserContact();
                query.setContactType(ContactType.USER.ordinal());
                query.setContactId(contactId);
                query.setStatus(UserContactStatus.FRIEND.ordinal());
                List<UserContact> userContacts = userContactMapper.selectUserContacts(query);
                msg.setContactType(type.ordinal());
                msg.setContactName(contactName);
                msg.setExtendedData(update);
                msg.setMessageType(MessageType.CONTACT_NAME_UPDATE.ordinal());
                msg.setSendUserId(contactId);
                msg.setSendUserNickName(contactName);
                for (UserContact userContact : userContacts) {
                    msg.setContactId(userContact.getUserId());
                    messageHandler.sendMsg(msg);
                }
            }
        }
    }
}
